import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as k
"""
卷积神经网络：不停的卷积和池化
	卷积
		卷积核：----在数据中自学：
		步长：可自定义
	池化：也叫下采样
		为什么池化：缩小图片尺寸，增强旋转不变性
		池化方式：1、平均值池化   2、最大值池化
	激活函数：softmax  或  relu
"""
if __name__ == "__main__":
	# 设置初始参数
	batch_size = 128  # 一次训练128张图片
	# 分类
	num_classes = 10
	# 迭代次数(训练次数)
	epochs = 12
	img_rows, img_cols = 28, 28
	# 加载数据
	(x_train, y_train), (x_test, y_test) = mnist.load_data()
	#  彩色通道3，灰度通道1
	if k.image_data_format() == 'channels_first':
		x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
		x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
		input_shape = (1, img_rows, img_cols)
	else:
		x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
		x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
		input_shape = (img_rows, img_cols, 1)
	# 处理数据
	x_train = x_train.astype('float32')
	x_test = x_test.astype('float32')
	x_train /= 255
	x_test /= 255

	y_train = keras.utils.to_categorical(y_train, num_classes=num_classes)
	y_test = keras.utils.to_categorical(y_test, num_classes=num_classes)
	# 选择序贯模型
	model = Sequential()
	# 几卷层1
	model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
	# 几卷层2
	model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
	# 池化
	model.add(MaxPooling2D(pool_size=(2, 3)))
	# 防止过拟合
	model.add(Dropout(0.25))
	# 压平
	model.add(Flatten())
	# 全连接
	model.add(Dense(128, activation='relu'))
	# 都丢掉50%的数据
	model.add(Dropout(0.5))
	# 全连接
	model.add(Dense(num_classes, activation='softmax'))
	# cnn的参数
	model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
	# 训练
	model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))
	# 测试
	score = model.evaluate(x_test, y_test, verbose=0)
